﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FluentValidation;
using Microhard.Core;
using FluentValidation.Results;
using Microhard.Plat.CRM.Customers.Models;
using Microhard.Plat.CRM.Customers.Msg;
using Microhard.Plat.CRM.Customers.Interface;

namespace Microhard.Plat.CRM.Customers.Validator
{
    public class ProductModelValidator : AbstractValidator<ProductModel>
    {
        public ProductModelValidator()
        {
            RuleSet("Insert", () =>
            {
                RuleFor(u => u.SN).NotEmpty().WithMessage(ProductMsg.NeedSN).When(r => r.ProductID == Guid.Empty);
                RuleFor(u => u.SN).Length(1, 50).WithMessage(ProductMsg.SNMaxLength).When(r => r.ProductID == Guid.Empty);

                RuleFor(u => u.Mark).NotEmpty().WithMessage(ProductMsg.NeedMark).When(r => r.ProductID == Guid.Empty);
                RuleFor(u => u.Mark).Length(1, 200).WithMessage(ProductMsg.MarkMaxLength).When(r => r.ProductID == Guid.Empty);

                Custom(u =>
                {
                    ICmpProduct prd = IoC.Resolve<ICmpProduct>();
                    if (prd.IsDuplicate(u))
                    {
                        return new ValidationFailure("SN", ProductMsg.DuplicateName);
                    }
                    if (u.IsPromotion)
                    {
                        if (u.CostCoin == 0)
                        {
                            return new ValidationFailure("CostCoin", ProductMsg.NeedCostCoin);
                        }
                    }
                    return null;
                });
            });

            RuleSet("Update", () =>
            {
                RuleFor(u => u.Mark).NotEmpty().WithMessage(ProductMsg.NeedMark).When(r => r.ProductID == Guid.Empty);
                RuleFor(u => u.Mark).Length(1, 200).WithMessage(ProductMsg.MarkMaxLength).When(r => r.ProductID == Guid.Empty);

                Custom(u =>
                {
                    ICmpProduct prd = IoC.Resolve<ICmpProduct>();
                    if (prd.IsDuplicate(u))
                    {
                        return new ValidationFailure("SN", ProductMsg.DuplicateName);
                    }
                    if (u.IsPromotion)
                    {
                        if (u.CostCoin == 0)
                        {
                            return new ValidationFailure("CostCoin", ProductMsg.NeedCostCoin);
                        }
                    }
                    return null;
                });
            });
        }
    }
}
